//
//  SpBhNext.m
//  Bus
//
//  Created by wangjiajia on 13-12-16.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "SpBhNext.h"
#import "UserForm.h"
#import "UIButton+Bootstrap.h"
#import "DropDownView.h"
#import "WebServicesUtils.h"
#import "ASIHTTPRequest.h"
#import "MBProgressHUD.h"
#import "Tools.h"
#import "JsonParser.h"
#import "WorkFlowNode.h"
#import "NextStep.h"
#import "People.h"
#import "DepNode.h"
#import "ProcessResult.h"
#import "DXAlertView.h"
extern int userId;
extern NSString* userName;

@interface SpBhNext (){
    MBProgressHUD * hud;
    NSString* postNotification;
    WorkFlowNode* currentWorkFlowNode;
    WorkFlowNode* selectedWorkFlowNode;
    NSArray* jbrPeoples;//NSString数组
    NSArray* jbbmPeoples;//People数组
    NSArray* jbjsPeoples;//People数组
    NSString* pickViewIntent;
    BOOL isPop;//人员选择是否显示
    NSArray* spjsComponent0_Unit;//单位 NSString数组
    NSMutableArray* spjsComponent1_Deps;//部门 DepNode数组
    NSMutableArray* spjsComponent2_People;//人员 People数组
    //选择的人
    People* selectedPeople;
    NextStep* nextStep;
    
}

@end
@implementation SpBhNext
//@synthesize userForm;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    
    //广播identity
    postNotification=@"SpBhNext__Notification_selectChanged";
    //人员选择
    isPop=NO;
    //所有人员选择初始化(数据源只绑定第一次的内存地址,所以形参只能add，remove，不能重定向，否则失去内存句柄。)
    spjsComponent0_Unit=@[@"总公司机关",@"营运单位",@"二级单位"];
    spjsComponent2_People=[NSMutableArray arrayWithCapacity:10];
    
    //标题
    self.navigationItem.title=@"审批驳回";
    //单位-部门-人员
    spjsComponent0_Unit=@[@"总公司机关",@"营运单位",@"二级单位"];
    ////NSLog(@"number form nil=%d",spjsComponent2_People.count);//没有初始化，但没有空指针异常
    //返回按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back.png"] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back_selected.png"] forState:UIControlStateHighlighted];
    
    [leftButton setTitle:@" 返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"-" size:18];
    [leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = back;
    
    //表单基本信息
    NSString* info=[NSString  stringWithFormat:@"%@,流水号:%@,当前步骤:%@",self.userForm.Name,self.userForm.Sequence,self.userForm.UpNodeName];
    float wordWidth=[info sizeWithFont:[UIFont fontWithName:@"-"size:20]].width;
    float screenWidth=[UIScreen mainScreen].bounds.size.width;
    CGRect frame=self.spFormInfo.frame;
    frame.size.width=wordWidth>screenWidth?wordWidth:screenWidth;
    self.spFormInfo.frame=frame;
    self.spFormInfo.font=[UIFont fontWithName:@"-" size:20];
    self.spFormInfo.text=info;
    
    //提示字体
    UIFont* defaultFont=[UIFont fontWithName:@"-" size:18];
    self.chooseNextStepLable.font=defaultFont;
    self.jbrLable.font=defaultFont;
    self.jbbmLable.font=defaultFont;
    self.jbjsLable.font=defaultFont;
    self.spjsLable.font=defaultFont;
    
    //审批人员禁用键盘
    self.jbrTextField.delegate=self;
    self.jbbmTextField.delegate=self;
    self.jbjsTextField.delegate=self;
    self.spjsTextField.delegate=self;
    
    //按钮样式
    [self.jbrButton clearStyle];
    [self.jbbmButton clearStyle];
    [self.jbjsButton clearStyle];
    [self.spjsButton clearStyle];
    
    //滚动范围
    self.scrollView.contentSize=CGSizeMake(320, 418);
    //事件绑定
    [self initBtnBySelectedWorkFlowNode];
    //下一步骤下拉列表
    CGRect dropDownFrame=CGRectMake(120, 0, 200, 200);
    self.dropDown=[[DropDownView alloc] initWithFrame:dropDownFrame];
    self.dropDown.textField.placeholder=@"请选择下一步骤";
    //self.dropDown.tableArray=[NSMutableArray arrayWithObjects:@"收文件",@"公共",@"审批表", @"收文件",@"财务",nil];//这会导致只返回5个
    self.dropDown.postNotificationName=postNotification;//广播标识
    [self.scrollView addSubview:self.dropDown];
    //提交按钮
    [self.submit infoStyle];
    //驳回
    [self.submit addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    //PickView确定按钮
    //    UIButton* sure=[[UIButton alloc] initWithFrame:CGRectMake(110, self.choosePeople.frame.size.height, 100,30 )];
    //    [sure addTarget:self action:@selector(hidePickView:) forControlEvents:UIControlEventTouchUpInside];
    //    [sure clearStyle];
    //     sure.titleLabel.text=@"确定";
    //    [self.view addSubview:sure];
    [self.chooseSure infoStyle];
    [self.chooseSure setHidden:YES];
    [self.chooseSure addTarget:self action:@selector(choosePeople:) forControlEvents:UIControlEventTouchUpInside];
    //下拉列表改变监听(广播)
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectNextStepChanged:) name:postNotification object:nil];
    //step1:获取当前节点（not need）
    //    [WebServicesUtils getExecSingle:[NSString stringWithFormat:@"getWorkFlowNode @id=%@",self.userForm.UpNodeId] andTag:100 withDelegete:self];
    
    //step1:获取驳回节点列表
    [WebServicesUtils getExec:[NSString stringWithFormat:@"proc_transaction_getBhNextStep @id=%@",self.userForm.Id] andTag:101 withDelegete:self];
    [self loading];
    
    
    
    
}

-(void)loading{
    if(!hud)
    {
        hud=[[MBProgressHUD alloc] initWithView:self.view];
        //hud.labelFont=[UIFont fontWithName:@"-" size:16];//放在默认里面
    }
    [Tools showHUD:@"正在获取数据..." andView:self.view andHUD:hud];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- 逻辑处理
//-(void)initUIByCurrentWorkFlowNode:(WorkFlowNode*)node{
//    if([node.nodeSite isEqualToString:@"结束"]){
//        self.scrollView.hidden=YES;
//        UILabel* labelInfo=[[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 30)];
//        labelInfo.text=@"当前步骤为结束";
//        labelInfo.backgroundColor=UIColorFromRGBA(0x00000055);
//        labelInfo.textColor=[UIColor blueColor];
//        labelInfo.textAlignment=NSTextAlignmentCenter;
//        labelInfo.font=[UIFont fontWithName:@"-" size:22];
//        [self.view addSubview:labelInfo];
//
//        CGRect frame=self.submit.frame;
//        frame.origin.y=150;
//        self.submit.frame=frame;
//    }else{//中间段
//        //step2 获取下一步骤
//        [WebServicesUtils getExec:[NSString stringWithFormat:@"proc_transaction_getNextStep @id=%@",self.userForm.Id] andTag:101 withDelegete:self];
//        //[self loading];
//    }
//}

-(void)initBtnBySelectedWorkFlowNode{
    
    [self.jbrButton addTarget:self action:@selector(jbrButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.jbbmButton addTarget:self action:@selector(jbbmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.jbjsButton addTarget:self action:@selector(jbjsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.spjsButton addTarget:self action:@selector(spjsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)initUIBySelectedWorkFlowNode:(WorkFlowNode*)node{
    if(node){
        [self.jbrButton setTitle:@"[选择审批人员]" forState:UIControlStateNormal];
        [self.jbrButton setTitle:@"[选择审批人员]" forState:UIControlStateHighlighted];
        [self.jbbmButton setTitle:@"[选择审批人员]" forState:UIControlStateNormal];
        [self.jbbmButton setTitle:@"[选择审批人员]" forState:UIControlStateHighlighted];
        [self.jbjsButton setTitle:@"[选择审批人员]" forState:UIControlStateNormal];
        [self.jbjsButton setTitle:@"[选择审批人员]" forState:UIControlStateHighlighted];
        [self.spjsButton setTitle:@"[选择审批人员]" forState:UIControlStateNormal];
        [self.spjsButton setTitle:@"[选择审批人员]" forState:UIControlStateHighlighted];
        
        self.jbrTextField.text=node.jbrObjectName;
        self.jbbmTextField.text=node.jbbmObjectName;
        self.jbjsTextField.text=node.jbjsObjectName;
        
        jbrPeoples=[node.jbrObjectName componentsSeparatedByString:@","];
        //jbbmPeoples=[node.jbbmObjectName componentsSeparatedByString:@","];
        //jbjsPeoples=[node.jbjsObjectName componentsSeparatedByString:@","];
        //网络获取经办人(由于数据量较小，没必要等到点击时再获取)
        if(![node.jbbmObjectId isEqualToString:@"0"])
            [WebServicesUtils getExec:[NSString localizedStringWithFormat:@"getJBBMPeoples @depids='%@'",node.jbbmObjectId] andTag:103 withDelegete:self];
        if(![node.jbjsObjectId isEqualToString:@"0"])
            [WebServicesUtils getExec:[NSString localizedStringWithFormat:@"getJBJSPeoples @roleids='%@'",node.jbjsObjectId] andTag:104 withDelegete:self];
        
    }else{
        [self.jbrButton setTitle:@"[驳回给发起人]" forState:UIControlStateNormal];
        [self.jbrButton setTitle:@"[驳回给发起人]" forState:UIControlStateHighlighted];
        [self.jbbmButton setTitle:@"[驳回给发起人]" forState:UIControlStateNormal];
        [self.jbbmButton setTitle:@"[驳回给发起人]" forState:UIControlStateHighlighted];
        [self.jbjsButton setTitle:@"[驳回给发起人]" forState:UIControlStateNormal];
        [self.jbjsButton setTitle:@"[驳回给发起人]" forState:UIControlStateHighlighted];
        [self.spjsButton setTitle:@"[驳回给发起人]" forState:UIControlStateNormal];
        [self.spjsButton setTitle:@"[驳回给发起人]" forState:UIControlStateHighlighted];
        
        self.jbrTextField.text=@"";
        self.jbbmTextField.text=@"";
        self.jbjsTextField.text=@"";
    }
    //UITextField不能多行,这里设置貌似没有用哎
    self.jbrTextField.adjustsFontSizeToFitWidth=YES;
    self.jbbmTextField.adjustsFontSizeToFitWidth=YES;
    self.jbjsTextField.adjustsFontSizeToFitWidth=YES;
    self.spjsTextField.adjustsFontSizeToFitWidth=YES;
    
}

-(void)selectNextStepChanged:(NSNotification*)notification{
    int index=[(NSString*)notification.object intValue];
    nextStep=(NextStep*)[self.dropDown.tableArray objectAtIndex:index];
    
    if(index>0){
        [WebServicesUtils getExecSingle:[NSString stringWithFormat:@"getWorkFlowNode @id=%d",nextStep.nodeId] andTag:102 withDelegete:self];
    }else{//开始
        selectedWorkFlowNode=nil;
        [self initUIBySelectedWorkFlowNode:selectedWorkFlowNode];
        selectedPeople=nil;
        self.spjsTextField.text=@"";
        
        
    }
    ////NSLog(@"选择了第%d个,%d:%@",index,nextStep.nodeId,nextStep.nodeName);
}

-(void)choosePeople:(id)sender{
    [self hidePickView];
    //还原
    self.spjsTextField.text=@"";
    selectedPeople=nil;
    //选择的行
    int row=0;
    if(![pickViewIntent isEqualToString:@"spjs"])
        row= [self.choosePeople selectedRowInComponent:0];//其他接受人员 取第1列选择行
    else
        row= [self.choosePeople selectedRowInComponent:2];//审批接受人员 取第2列选择行
    
    if([pickViewIntent isEqualToString:@"jbr"])
    {
        NSString*   name= [NSString stringWithFormat:@"%@", [jbrPeoples objectAtIndex:row]];
        int   peopleId=[[[selectedWorkFlowNode.jbrObjectId componentsSeparatedByString:@","] objectAtIndex:row] intValue];
        selectedPeople=[[People alloc] initwithParams:peopleId andUserName:name];
        
    }
    else if([pickViewIntent isEqualToString:@"jbbm"]){
        if(jbbmPeoples)
            selectedPeople=   (People*) [jbbmPeoples objectAtIndex:row];
        
    }else if([pickViewIntent isEqualToString:@"jbjs"]){
        if(jbjsPeoples)
            selectedPeople= (People*) [jbjsPeoples objectAtIndex:row];
        
    }else if([pickViewIntent isEqualToString:@"spjs"]){
        //[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array,所以加上一个count>0的判断。
        if(spjsComponent2_People&&spjsComponent2_People.count>0)
            selectedPeople= (People*) [spjsComponent2_People objectAtIndex:row];
        
    }
    //人员多选
    //self.spjsTextField.text=[NSString stringWithFormat:@"%@%@,",self.spjsTextField.text,name];
    //人员单选
    if(selectedPeople)
        self.spjsTextField.text=[NSString stringWithFormat:@"%@,",selectedPeople.userName];
    else
        [Tools toastNotification:@"没有选择人员." andView:self.view andLoading:NO andIsBottom:NO];
}

-(void)submit:(id)sender{
    if(nextStep&&nextStep.nodeId>0&&!selectedPeople){
        [Tools toastNotification:@"请选择审批接受人员" andView:self.view andLoading:NO andIsBottom:NO];
    }else{
        NSString* info;
        if(!nextStep||nextStep.nodeId==0){
            info=@"确定驳回到流程开始?";
        }else {
            info =[NSString stringWithFormat:@"确定将该表单驳回给<%@>?",selectedPeople.userName];
        }
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"审批驳回" contentText:info leftButtonTitle:@"确定" rightButtonTitle:@"取消"];
        
        alert.leftBlock = ^() {
            //驳回给发起人 或者 指定人
            
            [WebServicesUtils processReject:self.userForm.Id andUserId:[NSString stringWithFormat:@"%d",userId] andUserName:userName andJbrUserId:selectedPeople?[NSString stringWithFormat:@"%d",selectedPeople.userId]:@"" andJbrUserName:selectedPeople?[NSString stringWithFormat:@"%@",selectedPeople.userName]:@"" andSelectNodeValue:[NSString stringWithFormat:@"%d",nextStep.nodeId] withDelegete:self];
            
        };
        alert.rightBlock = ^() {
            
        };
        alert.dismissBlock = ^() {
            
        };
        [alert show];
    }
}

#pragma mark- 按钮点击事件处理
-(void)jbrButtonClick:(id)sender{
    ////NSLog(@"jbrButtonClick");
    UIButton* btn=(UIButton*)sender;
    if([btn.titleLabel.text isEqualToString:@"[驳回给发起人]"]){
        [Tools toastNotification:@"驳回给发起人!" andView:self.view andLoading:NO andIsBottom:NO];
    }
    else if(selectedWorkFlowNode==nil||[@"0" isEqualToString:selectedWorkFlowNode.jbrObjectId]||[@"未设置" isEqualToString:selectedWorkFlowNode.jbrObjectName]||[@"" isEqualToString:selectedWorkFlowNode.jbrObjectName]){
        
        [Tools toastNotification:@"未设置" andView:self.view andLoading:NO andIsBottom:NO];
    }   else{//UIPickerView
        pickViewIntent=@"jbr";
        //加入了isPop的判断，jbrButton即使不临时禁用，也OK
        if(!isPop)
            [self popPickView];
        else
            [self hidePickView];
        
    }
}

-(void)jbbmButtonClick:(id)sender{
    UIButton* btn=(UIButton*)sender;
    if([btn.titleLabel.text isEqualToString:@"[驳回给发起人]"]){
        [Tools toastNotification:@"驳回给发起人!" andView:self.view andLoading:NO andIsBottom:NO];
    }
    else
        if(selectedWorkFlowNode==nil||[@"0" isEqualToString:selectedWorkFlowNode.jbbmObjectId]||[@"未设置" isEqualToString:selectedWorkFlowNode.jbbmObjectName]||[@"" isEqualToString:selectedWorkFlowNode.jbbmObjectName]){
            
            [Tools toastNotification:@"未设置" andView:self.view andLoading:NO andIsBottom:NO];
        }else{//UIPickerView
            pickViewIntent=@"jbbm";
            if(!isPop)
                [self popPickView];
            else
                [self hidePickView];
        }
}

-(void)jbjsButtonClick:(id)sender{
    UIButton* btn=(UIButton*)sender;
    if([btn.titleLabel.text isEqualToString:@"[驳回给发起人]"]){
        [Tools toastNotification:@"驳回给发起人!" andView:self.view andLoading:NO andIsBottom:NO];
    }
    
    else if(selectedWorkFlowNode==nil||[@"0" isEqualToString:selectedWorkFlowNode.jbjsObjectId]||[@"未设置" isEqualToString:selectedWorkFlowNode.jbjsObjectName]||[@"" isEqualToString:selectedWorkFlowNode.jbjsObjectName]){
        
        [Tools toastNotification:@"未设置" andView:self.view andLoading:NO andIsBottom:NO];
    }else{//UIPickerView
        //点击时再获取,则需要如下判断
        //如果jbbmPeoples==nil，则发请求并return->处理请求结果，为jbbmPeoples赋值->手动触发click事件->jbbmPeoples==nil不满足，执行后续逻辑。
        
        pickViewIntent=@"jbjs";
        if(!isPop)
            [self popPickView];
        else
            [self hidePickView];
    }
}
//Android中点击事件是匿名函数，基于上下文环境，绑定比较方便！这里是单独的一个函数，不是基于上下文直接绑定，需要注意上下文的逻辑了。
-(void)spjsButtonClick:(id)sender{
    UIButton* btn=(UIButton*)sender;
    if([btn.titleLabel.text isEqualToString:@"[驳回给发起人]"]){
        [Tools toastNotification:@"驳回给发起人!" andView:self.view andLoading:NO andIsBottom:NO];
    }else if([btn.titleLabel.text isEqualToString:@"[选择审批人员]"]){
        //所有人员选择
        pickViewIntent=@"spjs";
        //初始化必须的数据
        if(spjsComponent1_Deps){
            if(!isPop)
                [self popPickView];
            else
                [self hidePickView];
        }else{
            //spjsComponent1_Deps数据初始化，结束后再执行后续逻辑。
            //为了确保顺序，可以使用NSMutableArray，发送有序请求，顺序添加。 或者Dictionary，发送无序请求，但指定有序的key。这里使用有序请求。
            spjsComponent1_Deps=[NSMutableArray arrayWithCapacity:3];//初始化，避免nil异常
            [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=1" andTag:105 withDelegete:self];
            
        }
        
    }
}

#pragma mark- 显示与隐藏
-(void)popPickView{
    isPop=YES;//加入了isPop的判断，jbrButton即使不临时禁用，逻辑也OK
    self.jbrButton.enabled=NO;//临时禁用该按钮
    self.jbbmButton.enabled=NO;
    self.jbjsButton.enabled=NO;
    //刷新数据
    //[self.choosePeople reloadComponent:0];
    [self.choosePeople reloadAllComponents];
    ////NSLog(@"pop");
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"show" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    [self.view bringSubviewToFront:self.choosePeople];
    [self.view bringSubviewToFront:self.chooseSure];
    CGRect frame=self.choosePeople.frame;
    frame.origin.y+=frame.size.height;
    self.choosePeople.frame =frame;
    
    CGRect sureFrame=self.chooseSure.frame;
    sureFrame.origin.y+=frame.size.height;
    self.chooseSure.frame=sureFrame;
    
    self.chooseSure.hidden=NO;
    [UIView setAnimationDelegate:self];
    
    [UIView commitAnimations];
    
}

-(void)hidePickView{
    ////NSLog(@"hide");
    isPop=NO;
    self.jbrButton.enabled=YES;
    self.jbbmButton.enabled=YES;
    self.jbjsButton.enabled=YES;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"hide" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位
    CGRect frame=self.choosePeople.frame;
    frame.origin.y-=frame.size.height;
    self.choosePeople.frame =frame;
    
    CGRect sureFrame=self.chooseSure.frame;
    sureFrame.origin.y-=frame.size.height;
    self.chooseSure.frame=sureFrame;
    self.chooseSure.hidden=YES;
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}
#pragma mark- UIPickerViewDataSource

// 返回显示的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if([pickViewIntent isEqualToString:@"spjs"])
        return 3;
    else
        return 1;
}

// 返回每一列中，显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    int count=0;
    if([pickViewIntent isEqualToString:@"jbr"])
    {
        count= jbrPeoples.count-1;//不要最后一个空""
    }
    else if([pickViewIntent isEqualToString:@"jbbm"]){
        count=jbbmPeoples.count;
    }else if([pickViewIntent isEqualToString:@"jbjs"]){
        count=jbjsPeoples.count;
    }else if([pickViewIntent isEqualToString:@"spjs"]){
        switch (component) {
            case 0:
                count=spjsComponent0_Unit.count;
                break;
            case 1:
            {
                NSInteger selectedRow=[self.choosePeople selectedRowInComponent:0];
                if(spjsComponent1_Deps&&spjsComponent1_Deps.count>0)
                {
                    NSMutableArray* deps=((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]);
                    if(deps&&deps.count>0)
                    {
                        count=deps.count;
                    }
                }
            }
                break;
            case 2:
                count=spjsComponent2_People.count;
                break;
        }
    }
    return count;
}

#pragma mark- UIPickerViewDelegate
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    //实测发现，这里宽度设置优先级高于 reusingView
    switch (component) {
        case 0:
            return 100;
        case 1:
            return 120;
        case 2:
            return 80;
        default:
            return 100;
    }
    //或者
    //return 100;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    //使用自定义的视图来替换默认的 实现尺寸大小、字体的设置，优先级高于pickerView:titleForRow:forComponent:
    UILabel* infoLabel=  view?(UILabel*)view:[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
    infoLabel.font=[UIFont fontWithName:@"-" size:14];
    infoLabel.textAlignment=NSTextAlignmentCenter;
    infoLabel.backgroundColor=UIColorFromRGBA(0x88888844);
    NSString* name;
    if([pickViewIntent isEqualToString:@"jbr"])
    {
        name= [NSString stringWithFormat:@"%@", [jbrPeoples objectAtIndex:row]];
    }
    else if([pickViewIntent isEqualToString:@"jbbm"]){
        name= ((People*)[jbbmPeoples objectAtIndex:row]).userName;
        
    }else if([pickViewIntent isEqualToString:@"jbjs"]){
        name= ((People*)[jbjsPeoples objectAtIndex:row]).userName;
        
    }else if([pickViewIntent isEqualToString:@"spjs"]){
        //switch Component 展示数据
        switch (component) {
            case 0:
            {
                name= [spjsComponent0_Unit objectAtIndex:row];//row=0,1,2 遍历
                //infoLabel.frame=CGRectMake(0, 0, 100, 30);
            }
                break;
            case 1:
            {
                NSInteger selectedRow=[self.choosePeople selectedRowInComponent:0];
                //这里有越界风险,加个判断
                if(((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]).count>row){
                    name= ((DepNode*)[((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]) objectAtIndex:row]).depName;}
                ////NSLog(@"%@-%@",[spjsComponent0_Unit objectAtIndex:selectedRow],name);
                //infoLabel.frame=CGRectMake(0, 0, 120, 30);
            }
                break;
            case 2:
            {
                if(spjsComponent2_People&&spjsComponent2_People.count>row)
                    name= ((People*)[spjsComponent2_People objectAtIndex:row]).userName;
                //infoLabel.frame=CGRectMake(0, 0, 80, 30);
            }
                break;
        }
        
    }
    
    
    infoLabel.text=name;
    return infoLabel;
    
}
//展示数据的核心代码
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString* name;
    if([pickViewIntent isEqualToString:@"jbr"])
    {
        name= [NSString stringWithFormat:@"%@", [jbrPeoples objectAtIndex:row]];
    }
    else if([pickViewIntent isEqualToString:@"jbbm"]){
        name= ((People*)[jbbmPeoples objectAtIndex:row]).userName;
        
    }else if([pickViewIntent isEqualToString:@"jbjs"]){
        name= ((People*)[jbjsPeoples objectAtIndex:row]).userName;
        
    }else if([pickViewIntent isEqualToString:@"spjs"]){
        //switch Component 展示数据
        switch (component) {
            case 0:
                name= [spjsComponent0_Unit objectAtIndex:row];//row=0,1,2 遍历
                break;
            case 1:
            {
                NSInteger selectedRow=[self.choosePeople selectedRowInComponent:0];
                
                name= ((DepNode*)[((NSMutableArray*)[spjsComponent1_Deps objectAtIndex:selectedRow]) objectAtIndex:row]).depName;
                ////NSLog(@"%@-%@",[spjsComponent0_Unit objectAtIndex:selectedRow],name);
            }
                break;
            case 2:
                name= ((People*)[spjsComponent2_People objectAtIndex:row]).userName;
                break;
        }
        
    }
    return name;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //初始化时候，会自动选择第一个,但不会触发该事件!只有手动选择才会触发。
    ////NSLog(@"didSelectRow");
    NSString* name;
    if([pickViewIntent isEqualToString:@"jbr"])
    {
        name= [NSString stringWithFormat:@"%@", [jbrPeoples objectAtIndex:row]];
    }
    else if([pickViewIntent isEqualToString:@"jbbm"]){
        name= [NSString stringWithFormat:@"%@", ((People*)[jbbmPeoples objectAtIndex:row]).userName];
        
    }else if([pickViewIntent isEqualToString:@"jbjs"]){
        name= [NSString stringWithFormat:@"%@", ((People*)[jbjsPeoples objectAtIndex:row]).userName];
        
    }else if([pickViewIntent isEqualToString:@"spjs"]){
        
        switch (component) {
            case 0:
                //refresh 1 then refresh 2
            {
                [self.choosePeople reloadComponent:1];
                [self getPeoplesDateAndRefreshComponent2];
            }
                break;
            case 1:
                // just refresh 2
                [self getPeoplesDateAndRefreshComponent2];
                break;
            case 2:
                if(spjsComponent2_People.count>row)
                    name=((People*)[spjsComponent2_People objectAtIndex:row]).userName;
                
        }
    }
    //if(name)
     //   NSLog(@"选择了%@",name);
}
#pragma mark- 先获取数据，再refresh 2
-(void)getPeoplesDateAndRefreshComponent2{
    NSInteger unit_index=[self.choosePeople selectedRowInComponent:0];
    NSInteger dep_index=[self.choosePeople selectedRowInComponent:1];
    
    if(spjsComponent1_Deps&&spjsComponent1_Deps.count>0){
        NSMutableArray* deps=  (NSMutableArray*)[spjsComponent1_Deps objectAtIndex:unit_index];
        if(deps&&deps.count>0){
            DepNode* depNode=(DepNode*)[deps objectAtIndex:dep_index];
            [WebServicesUtils getExec:[NSString stringWithFormat:@"getDepPeoples @depid=%d",depNode.depId] andTag:108 withDelegete:self];
        }
    }
    
}
#pragma mark- 返回到上一个视图
-(void)backTo{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark- 禁用键盘

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

#pragma mark- 网络处理

-(void)requestFinished:(ASIHTTPRequest *)request{
    if(hud){
        [hud hide:YES];
    }
    if(request.tag==100){//当前节点(not need)
        NSString * responseStr=[request responseString];
        ////NSLog(@"100%@", responseStr);//json字符串
        currentWorkFlowNode=[JsonParser parseAsWorkFlowNode:responseStr];
        //[self initUIByCurrentWorkFlowNode:currentWorkFlowNode];
        //[self initBtnByCurrentWorkFlowNode:currentWorkFlowNode];
    }else if(request.tag==101){//获取下一步骤列表
        NSString * responseStr=[request responseString];
        ////NSLog(@"%@", responseStr);//json字符串
        self.dropDown.tableArray=[JsonParser parseAsNextStep:responseStr];
        [self.dropDown.tableArray insertObject: [[NextStep alloc] initwithParams:0 andNodeName:@"开始"] atIndex:0];
        [self.dropDown.tv reloadData];
        if(self.dropDown.tableArray.count>0){
            [self.dropDown.tv selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];//默认选择第一个,该方法没有触发didSelectRowAtIndexPath,所以textField不会赋值,所以只好人为赋值为列表第1个值 [self.dropDown.tableArray objectAtIndex:0]
            //自动选择第一个 [结束]
            nextStep=(NextStep*)[self.dropDown.tableArray objectAtIndex:0];//全局nextStep赋值
            self.dropDown.textField.text=nextStep.nodeName;
            selectedWorkFlowNode=nil;
            [self initUIBySelectedWorkFlowNode:selectedWorkFlowNode];
            //step3:自动获取当前步骤详情(对于‘结束’节点而言 not need)
            //  [WebServicesUtils getExecSingle:[NSString stringWithFormat:@"getWorkFlowNode @id=%d",nextStep.nodeId] andTag:102 withDelegete:self];
        }
    }else if(request.tag==102){
        NSString * responseStr=[request responseString];
        ////NSLog(@"102%@", responseStr);//json字符串
        selectedWorkFlowNode=[JsonParser parseAsWorkFlowNode:responseStr];
        [self initUIBySelectedWorkFlowNode:selectedWorkFlowNode];//全局变量，也可以不用形参
        
    }else if(request.tag==103){//经办部门
        NSString * responseStr=[request responseString];
        jbbmPeoples=   [JsonParser parseAsPeoples:responseStr];
        ////NSLog(@"103%@", jbbmPeoples);//json字符串
        
    }
    else if(request.tag==104){//经办角色
        NSString * responseStr=[request responseString];
        jbjsPeoples=   [JsonParser parseAsPeoples:responseStr];
        ////NSLog(@"104%@", jbjsPeoples);//json字符串
    }else if(request.tag==105){//总公司机关部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=2" andTag:106 withDelegete:self];
    }else if(request.tag==106){//营运单位部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        [WebServicesUtils getExec:@"select DepID,DepName from Bas_DepInfo where ParentNodesID=3" andTag:107 withDelegete:self];
    }else if(request.tag==107){//二级单位部门
        NSString * responseStr=[request responseString];
        [spjsComponent1_Deps addObject:[JsonParser parseAsDepNode:responseStr]];
        ////NSLog(@"%@",spjsComponent1_Deps);
        //手动触发click
        [self.spjsButton sendActionsForControlEvents:UIControlEventTouchUpInside];
        
    }else if(request.tag==108){//获取到部门人员数据
        NSString * responseStr=[request responseString];
        //为了持有绑定内存的句柄，形参只能add，remove。不能重定向?好吧，我想错了。
        //        [spjsComponent2_People removeAllObjects];
        //        [spjsComponent2_People addObjectsFromArray:[JsonParser parseAsPeoples:responseStr]];
        //可以重定向的，数据源只绑定第一次的内存地址，猜测错误。
        spjsComponent2_People=[JsonParser parseAsPeoples:responseStr];
        [self.choosePeople reloadComponent:2];
        
    }else if(request.tag==1){//驳回
        
        NSString* responseStr=[request responseString];
        ////NSLog(@"responseStr=%@",responseStr);
        ProcessResult* pr= [JsonParser parseAsProcessResult:responseStr];
        UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
        [Tools toastNotification:pr.msg andView:shareWindow andLoading:NO andIsBottom:NO andHideTime:5];
        if(pr.result==1){
            //返回待办列表
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    
    
    ////NSLog(@"下拉列表共有元素%i个", self.dropDown.tableArray.count);
    
}
-(void)requestFailed:(ASIHTTPRequest *)request{
    //NSLog(@"处理请求失败%@",request.responseString);
    if(hud){
        [hud hide:YES];
    }
    [Tools toastNotification:@"处理请求失败，请检查网络连接!" andView:self.view andLoading:NO andIsBottom:NO];
}
@end
